package com.lvkerry.ssm.mvc.controller;

import com.lvkerry.ssm.domain.ResponseObj;
import com.lvkerry.ssm.domain.User;
import com.lvkerry.ssm.service.UserService;
import com.lvkerry.ssm.util.GsonUtils;
import com.lvkerry.ssm.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Kerry on 17/10/23
 */

@Controller
@RequestMapping("/userAction")
public class UserController {


    @Autowired
    private UserService userService;


    /**
     * 登录接口
     *
     * @param req
     * @param user
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    public Object login(HttpServletRequest req, User user) {

        ResponseObj<User> responseObj;
        if (null == user) {
            responseObj = new ResponseObj<>();
            responseObj.setCode(ResponseObj.EMPUTY);
            responseObj.setMsg("登录信息不能为空");
            return GsonUtils.gson.toJson(responseObj);

        }
        if (StringUtils.isEmpty(user.getUserId()) || StringUtils.isEmpty(user.getUserPwd())) {
            responseObj = new ResponseObj<>();
            responseObj.setCode(ResponseObj.FAILED);
            responseObj.setMsg("用户名或密码不能为空");
            return GsonUtils.gson.toJson(responseObj);
        }

        //查找用户
        User tempUser = userService.findUserById(user.getUserId());
        if (null == tempUser) {
            responseObj = new ResponseObj<>();
            responseObj.setCode(ResponseObj.EMPUTY);
            responseObj.setMsg("用户不存在");
        } else {
            if (user.getUserPwd().equals(tempUser.getUserPwd())) {
                responseObj = new ResponseObj<>();
                responseObj.setCode(ResponseObj.OK);
                responseObj.setMsg(ResponseObj.OK_STR);
            } else {
                responseObj = new ResponseObj<>();
                responseObj.setCode(ResponseObj.FAILED);
                responseObj.setMsg("用户名或密码错误");
            }
        }
        return GsonUtils.gson.toJson(responseObj);
    }


    @ResponseBody
    @RequestMapping(value = "/registered", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    public Object registered(HttpServletRequest req, User user) {


        return "";
    }

}
